#!/bin/bash

echo "🚀 WebRTC 完整信令演示 - 启动脚本"
echo "=========================================="

# 获取本机IP
IP_ADDRESS=$(hostname -I | awk '{print $1}')
echo "📡 Ubuntu IP地址: $IP_ADDRESS"
echo ""

# 检查依赖
check_dependency() {
    if command -v $1 >/dev/null 2>&1; then
        echo "✅ $1 已安装"
        return 0
    else
        echo "❌ $1 未安装"
        return 1
    fi
}

echo "🔍 检查系统依赖..."
check_dependency node || { echo "请安装 Node.js: sudo apt install nodejs npm"; exit 1; }
check_dependency python3 || { echo "请安装 Python3: sudo apt install python3"; exit 1; }

# 进入项目目录
# cd ~/webrtc || { echo "❌ 找不到 webrtc-demo 目录"; exit 1; }
echo "📁 工作目录: $(pwd)"

# 停止现有服务
echo ""
echo "🛑 停止现有服务..."
pkill -f "node signaling-server.js" 2>/dev/null && echo "✅ 停止信令服务器"
pkill -f "python3 -m http.server" 2>/dev/null && echo "✅ 停止HTTP服务器"
sleep 2

# 启动服务
echo ""
echo "🔧 启动服务..."
echo "1. 启动信令服务器 (端口 8080)..."
node signaling-server.js &
SERVER_PID=$!
sleep 3

if ps -p $SERVER_PID > /dev/null; then
    echo "✅ 信令服务器启动成功 (PID: $SERVER_PID)"
else
    echo "❌ 信令服务器启动失败"
    exit 1
fi

echo "2. 启动HTTP服务器 (端口 8081)..."
python3 -m http.server 8081 --bind 0.0.0.0 &
HTTP_PID=$!
sleep 2

if ps -p $HTTP_PID > /dev/null; then
    echo "✅ HTTP服务器启动成功 (PID: $HTTP_PID)"
else
    echo "❌ HTTP服务器启动失败"
    exit 1
fi

# 保存PID到文件
echo $SERVER_PID > /tmp/webrtc_server.pid
echo $HTTP_PID > /tmp/webrtc_http.pid

echo ""
echo "=========================================="
echo "🎉 WebRTC演示环境启动完成！"
echo "=========================================="
echo "📊 服务信息:"
echo "   - 信令服务器: ws://$IP_ADDRESS:8080"
echo "   - HTTP服务器: http://$IP_ADDRESS:8081"
echo "   - 演示页面: http://$IP_ADDRESS:8081/index.html"
echo ""
echo "💻 访问说明:"
echo "   1. Ubuntu 访问: http://$IP_ADDRESS:8081/index.html"
echo "   2. Windows 访问: http://$IP_ADDRESS:8081/index.html"
echo ""
echo "🧪 测试流程:"
echo "   1. 两台设备都点击'连接信令服务器'"
echo "   2. Ubuntu端点击'创建Offer'"
echo "   3. Windows端点击'准备Answer'"
echo "   4. 观察NAT穿透和P2P连接建立"
echo "   5. 测试P2P消息通信"
echo "=========================================="
echo ""
echo "📝 监控命令:"
echo "   - 查看信令日志: tail -f 信令服务器终端"
echo "   - 检查网络连接: netstat -tunp | grep -E '(8080|8081)'"
echo "   - 停止服务: pkill -f 'node signaling-server.js' && pkill -f 'python3 -m http.server'"
echo ""
echo "⏹️  按 Ctrl+C 停止所有服务"

# 等待中断信号
cleanup() {
    echo ""
    echo "🛑 正在停止服务..."
    pkill -f "node signaling-server.js" 2>/dev/null && echo "✅ 停止信令服务器"
    pkill -f "python3 -m http.server" 2>/dev/null && echo "✅ 停止HTTP服务器"
    rm -f /tmp/webrtc_*.pid
    echo "✅ 所有服务已停止"
    exit 0
}

trap cleanup SIGINT

# 等待
wait